import Vue from 'vue'
// import vm from '../main.js'
import VueRouter from 'vue-router'
import request from '../httpConfig/httpConfig.js'
import { message } from 'ant-design-vue';
import LoginRegister from '../views/LoginRegister/LoginRegister.vue'
import Header from '../views/Header/Header.vue'
import Index from '../views/Index/Index.vue'
import Adopt from '../views/Adopt/Adopt.vue'
import Detail from '../views/Detail/Detail.vue'
import UserInfo from '../views/UserInfo/UserInfo.vue'
import Fosterage from '../views/Fosterage/Fosterage.vue'
import MyFosterage from '../views/Fosterage/MyFosterage/MyFosterage.vue'
import PublicFosterage from '../views/Fosterage/PublicFosterage/PublicFosterage.vue'

Vue.use(VueRouter)

const routes = [
  {
    name: 'LoginRegister',
    path: '/login',
    component: LoginRegister
  },
  {
    name: 'Header',
    path: '/',
    component: Header,
    children: [
      {
        name: 'Index',
        path: '',
        component: Index
      },
      {
        name: 'Adopt',
        path: 'adopt',
        component: Adopt
      },
      {
        name: 'Detail',
        path: 'detail',
        component: Detail
      },
      {
        name: 'UserIofo',
        path: 'userInfo',
        component: UserInfo,
        meta: {isAuth: true}
      },
      {
        name: 'Fosterage',
        path: 'fosterage',
        component: Fosterage,
        meta: {isAuth: true},
        children: [
          {
            name: 'MyFosterage',
            path: 'myFosterage',
            component: MyFosterage,
            meta: {isAuth: true}
          },
          {
            name: 'PublicFosterage',
            path: 'publicFosterage',
            component: PublicFosterage,
            meta: {isAuth: true}
          }
        ]
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // updateAvatar();
  // 判断转跳的路由是否需要鉴权
  if (to.meta.isAuth) {
    let token = localStorage.getItem('token');
    if (token) {
      request.post('/user/isLogin').then(res => {
        if (res.code == 200) {
          next();
        }else {
          message.error(res.msg);
        }
      })
    }else {
      message.error('您还未登录，请登录！');
    }
  } else {// 不需要鉴权时
    // updateAvatar();
    next();
  }
})

// function updateAvatar() {
//   // 每次路由转换之前都向后端验证一下是否已经登录
//   let token = localStorage.getItem('token');
//   // 如果已经登录，则获取用户头像回来
//   if (token) {
//     request.post('/user/isLogin').then(res => {
//       if (res.code == 200) {
//         // vm.$store.state.avatarPath = res.data.avatarPath;
//         // sessionStorage.setItem('avatarPath', res.data.avatarPath);
//       }else {
//         // vm.$store.state.avatarPath = '/img/loginAvatar.png';
//       }
//     })
//   }else {
//     // vm.$store.state.avatarPath = '/img/loginAvatar.png';
//   }
// }

export default router
